package edu.bbu.bibliospring.backend.service.beans;

import edu.bbu.bibliospring.backend.model.Author;
import edu.bbu.bibliospring.backend.repository.AuthorRepository;
import edu.bbu.bibliospring.backend.repository.exception.BibliospringRepositoryException;
import edu.bbu.bibliospring.backend.service.AuthorService;
import edu.bbu.bibliospring.backend.service.exception.BibliospringServiceException;

import javax.ejb.DependsOn;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

@Stateless(name = "AuthorService", mappedName = "ejb/AuthorService")
@DependsOn({"AuthorRepository", "Author"})
public class AuthorServiceBean implements AuthorService {

    private static final Logger LOG = Logger.getLogger(AuthorService.class.getName());

    @EJB
    private AuthorRepository authorRepository;

    @Override
    public List<Author> getAll() throws BibliospringServiceException {
        try {
            LOG.info("AuthorService - getAll");
            return authorRepository.getAll();
        } catch (BibliospringRepositoryException e) {
            LOG.log(Level.SEVERE, e.getMessage());
            throw new BibliospringServiceException("Author repository - getAll()", e);
        }
    }

    @Override
    public Author getById(Long id) throws BibliospringServiceException {
        try {
            LOG.info("AuthorService - getById");
            return authorRepository.getById(id);
        } catch (final BibliospringRepositoryException e) {
            LOG.log(Level.SEVERE, e.getMessage());
            throw new BibliospringServiceException("AuthorRepositoryBean - getById()", e);
        }
    }

    @Override
    public Author insertAuthor(Author author) throws BibliospringServiceException {
        try {
            LOG.info("AuthorService - insertAuthor");
            return authorRepository.save(author);
        } catch (final BibliospringRepositoryException e) {
            LOG.log(Level.SEVERE, e.getMessage());
            throw new BibliospringServiceException("AuthorRepositoryBean - insertAuthor()", e);
        }
    }

    @Override
    public Long deleteAuthor(Author author) throws BibliospringServiceException{
        try {
            LOG.info("AuthorService - deleteAuthor");
            Long l = authorRepository.delete(author);
            return 1l;
        } catch (BibliospringRepositoryException e) {
            LOG.log(Level.SEVERE, e.getMessage());
            throw new BibliospringServiceException("AuthorRepositoryBean - deleteAuthor()", e);
        }
    }

}
